package com.loocan.answer.view
import android.R
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.animation.AnticipateOvershootInterpolator
import androidx.appcompat.widget.AppCompatButton
import com.bytedance.sdk.openadsdk.core.z.tr

/**
 * 支持弹性动画的按钮（优化版）
 */
class AnimatedButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatButton(context, attrs, defStyleAttr) {

    companion object {
        private const val TAG = "AnimatedButton"
    }

    // 动画参数
    private val pressScale = 0.90f
    private val pressDuration = 100L
    private val releaseDuration = 200L
    private val interpolator = AnticipateOvershootInterpolator()

    // 动画控制器
    private var currentAnimator: AnimatorSet? = null

    private var onClickView: OnClickView? = null

    interface OnClickView {
        fun onClick(text: String)
    }

    fun settOnClickView(onClickView: OnClickView) {
        this.onClickView = onClickView
    }

    init {
        isClickable = true
        isFocusable = true
        elevation = 8f
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.d(TAG, "ACTION_DOWN")
                startPressAnimation()
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                Log.d(TAG, "ACTION_UP / ACTION_CANCEL")
                startReleaseAnimation()
                onClickView?.onClick(text.toString())
            }
        }
        return true // 强制消费事件
    }

    private fun startPressAnimation() {
        currentAnimator?.cancel() // 取消旧动画

        val scaleX = ObjectAnimator.ofFloat(this, "scaleX", pressScale)
        val scaleY = ObjectAnimator.ofFloat(this, "scaleY", pressScale)

        currentAnimator = AnimatorSet().apply {
            playTogether(scaleX, scaleY)
            duration = pressDuration
            start()
        }

        elevation = 4f // 按下时下沉
    }

    private fun startReleaseAnimation() {
        currentAnimator?.cancel()

        val scaleX = ObjectAnimator.ofFloat(this, "scaleX", 1f)
        val scaleY = ObjectAnimator.ofFloat(this, "scaleY", 1f)

        currentAnimator = AnimatorSet().apply {
            playTogether(scaleX, scaleY)
            duration = releaseDuration
            interpolator = this@AnimatedButton.interpolator
            start()
        }

        elevation = 8f // 恢复高度
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        currentAnimator?.cancel()
        currentAnimator = null
    }
}